<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/6
 * Time: 14:23
 */

namespace App\Http\Controllers\Home;

use App\Model\Apply;
use App\Model\GroupList;
use App\Model\GroupMember;
use App\Model\MicroMall;
use App\Model\Poundage;
use App\Model\ShopMemberCart;
use App\Model\ShopOrderComment;
use App\Model\ShoppingGoods;
use Illuminate\Http\Request;
use App\Model\ShopGoods;
use App\Model\ShopGoodsImg;
use App\Model\StoresCenter;
use App\Model\StoresCenterGoods;
use App\Model\ShopOrder;
use App\Model\ShopGoodsClassify;
use Illuminate\Support\Facades\DB;
use App\Model\Members;
use Illuminate\Support\Facades\Session;
use App\Model\MembersLevel;

class MicroShopController extends BaseController
{
    /**
     * 微商城
     */
    public function index()
    {
        //检测是否填写资料
        $user = session('home_user');
        $UserModel = new Members();
        $userInfo = $UserModel->where('uid', $user['uid'])->first();
        Session::put('home_user', $userInfo);
        if (empty($userInfo['phone']) || empty($userInfo['user_name'])) {
            return redirect('home/member/userInfo')->withErrors('请完善个人资料');
        }
//        $userLeve = MembersLevel::where('id',$user['level'])->first();
//        if($user['credit3']>$userLeve['credit3']){
//            return redirect('home/straightShop/index')->withErrors('请复投');
//        }
        return view('Home.micro.microShop');
    }

    /**
     * 微商城商品
     * @param Request $request
     * @return array
     */
    public function smallShop(Request $request)
    {
        $data = $request->all();
        $user = session('home_user');
        if (empty($data)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        switch ($data['class']) {
            case 'select': //查询
                $table = ShopGoodsClassify::where(['type' => 2])->select('id');
                $classify = $table->get()->toArray();
                $pid = [];
                if (!empty($classify)) {
                    foreach ($classify as $value) {
                        $pid[] = $value['id'];
                    }
                } else {
                    return ['code' => 0, 'data' => '暂时还没有商品'];
                }

                //查询出所有分类
                $classifyDate = ShopGoodsClassify::where(['type' => 2, 'pid' => 1])->select('id', 'name')->orderBy('id', 'desc')->get()->toArray();
                $classifyFirst = ShopGoodsClassify::where(['type' => 2, 'pid' => 1])->orderBy('id', 'desc')->limit(1)->value('id');
                $classifysFirst = $data["two_tid"] != 0 ? $data["two_tid"] : $classifyFirst;
                //查询商品
                $shop = ShopGoods::where(['type' => 1, 'status' => 1, 'cid' => 1])->paginate(8);

//                $shop = ShoppingGoods::join('shop_goods', 'shop_goods.id', '=', 'shopping_goods.gid')
//                    ->select(
//                        'shop_goods.*',
//                        'shopping_goods.actual_num',
//                        'shopping_goods.buy_num',
//                        'shopping_goods.start_time',
//                        'shopping_goods.end_time',
//                        'shopping_goods.id as group_id'
//                    )
//                     ->where('shop_goods.cid','=',1)
//                     ->where('shop_goods.status','=',1)
//                     ->where('shop_goods.type','=',1)
//                    ->paginate(10);
                //随机轮播图
                $rotation = ShopGoodsImg::join('shop_goods','shop_goods.id','=','shop_goods_img.gid')
                    ->join('shop_goods_classify','shop_goods.cid','=','shop_goods_classify.id')
                    ->select(
                        'shop_goods_img.gid','shop_goods_img.img'
                    )
                    ->where(['shop_goods.type' => 1,'shop_goods.status' => 1,'shop_goods_classify.type' => 2])
                    ->groupBy('shop_goods_img.gid')
                    ->inRandomOrder()
                    ->take(2)
                    ->get()
                    ->toArray();
//                ShopGoodsImg::select('gid','img')->where('gid','!=',0)->inRandomOrder()->take(2)->get()->toArray();
                if ($shop) {
                    foreach ($shop as $k => $value) {
                        $img = ShopGoodsImg::where(['gid' => $value['id']])->select('img')->first();
                        $shop[$k]['img'] = empty($img->img) ? '' : $img->img;

//                        $shop[$k]['info'] = array_slice($shop,1,2);
//                        var_dump( $shop);exit;
                    }
                    return ['code' => 1, 'data' => $shop, 'classifyDate' => $classifyDate, 'classifyFirst' => $classifysFirst ,'rotation' => $rotation];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;
            case 'package':
                $res = ShopGoods::where(['number' => '00006', 'status' => 1])->first();
                if ($res) {
                    $img = ShopGoodsImg::where(['gid' => $res['id']])->select('img')->first();
                    $res['img'] = empty($img->img) ? '' : $img->img;
//                    $resultData = ShopOrderComment::join('shop_order', 'shop_order.id', '=', 'shop_order_comment.orderid')
//                        ->where('shop_order_comment.goodsid',$res['id'])
//                        ->where('shop_order.status', '>=', 1)
//                        ->where('shop_order.uid', $user['uid'])
//                        ->first();
//                    if (!empty($resultData)) {
//                        $res['pay_status'] = 1;
//                    } else {
//                        $res['pay_status'] = 0;
//                    }
                    return ['code' => 1, 'data' => $res];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;

        }
    }

    /**
     * 购物车操作
     * @param Request $request
     * @return array
     */
    public function car(Request $request)
    {
        $data = $request->all();
        if (empty($data)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        $ShopGoodsModel = new ShopGoods();
        $ShopMemberCart = new ShopMemberCart();
        $user = session('home_user');
        $uid = $user->uid;
        switch ($data['class']) {
            case 'add':

                if ($data['specsExist'] == 1 && $data['specs'] == '') {
                    return ['code' => 0, 'data' => '请选择产品规格'];
                }
                if ($data['specsExist'] == 1) {
                    if ($data['specslength'] != $data['Checklength']) {
                        return ['code' => 0, 'data' => '请完整选择产品规格!'];
                    }
                }

                $cartGoods = $ShopMemberCart->find_cart($uid, $data['goodsid']);
                $isAddCartGoods = 0;
                if ($data['specs'] != '') {
                    $carSpecsExist = ShopMemberCart::where(['specs' => $data['specs']])->select('uid', 'goodsid', 'number')->first();
                    if ($carSpecsExist['uid'] == $uid && $carSpecsExist['goodsid'] == $data['goodsid']) {
                        $cartGoodsExist = 1;
                    } else {
                        $cartGoodsExist = 0;
                    }
                    if ($cartGoods && $cartGoodsExist == 1) {
                        $rico = ShopMemberCart::where(['specs' => $data['specs'], 'uid' => $uid, 'goodsid' => $data['goodsid']])->increment('number', $data['number']);
                        $isAddCartGoods = 1;
                    }
                } else {
                    if ($cartGoods) {
                        $cartGoods->number += $data['number'];
                        $rico = $cartGoods->save();
                        $isAddCartGoods = 1;
                    }
                }

                if ($isAddCartGoods != 1) {
                    //有商品更改数量
                    $goods = $ShopGoodsModel->find_shop($data['goodsid']);
                    $carData = [
                        'uid' => $user->uid,
                        'openid' => $user->openid,
                        'goodsid' => $data['goodsid'],
                        'goodsname' => $goods['goodsname'],
                        'number' => $data['number'],
                        'rulingprice' => $goods['rulingprice'],
                        'specs' => $data['specs'],
                        'createtime' => time(),
                    ];
                    $rico = $ShopMemberCart->add_cart($carData);
                }

                if ($rico) {
                    return ['code' => 1, 'data' => '添加成功'];
                } else {
                    return ['code' => 0, 'data' => '添加失败'];
                }
                break;
        }
    }

    /**
     * 付款页面
     */
    public function productMicro()
    {
        return view('Home.micro.productMicro');
    }

    /**
     * 特价专区商品详情
     */
    public function microProduct()
    {
        return view('Home.micro.micProduct');
    }

    /**
     * 特价专区订单
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function microOrder(Request $request)
    {
        $data = $request->all();
        if (empty($data)) {
            return ['code' => 0, 'data' => '没有数据'];
        }
        $user = session('home_user');
        //商品表
        $ShopGoodsModel = new ShopGoods();
        //复销折扣
        $microMallModel = new MicroMall();
        $microMall = $microMallModel->get()->toArray();
        //订单表
        $ShopOrderModel = new ShopOrder();
        //订单详情表
        $ShopOrderCommentModel = new ShopOrderComment();
        //购物车表
        $ShopMemberCartModel = new ShopMemberCart();
        switch ($data['class']) {
            case 'add': //添加
                if (empty($data['goods'])) {
                    return ['code' => 0, 'data' => '没有商品'];
                }
                $goodsIds = [];
                foreach ($data['goods'] as $k => $v) {
                    if (intval($v['number']) < 1 || intval($v['number']) == '') {
                        return ['code' => 0, 'data' => '数量错误'];
                        break;
                    }

                    $goodsIds[] = $v['goodsid'];
                }


                if (isset($data['type'])) {
                    $specs = $data['goods'][0]['specs'];
                    $specslength = $data['specslength'];
                    $Checklength = $data['Checklength'];
                    $specsExist = $data['specsExist'];
                    if ($specsExist == 1 && $specs == '') {
                        return ['code' => 0, 'data' => '请选择产品规格'];
                    }
                    if ($specsExist == 1) {
                        if ($specslength != $Checklength) {
                            return ['code' => 0, 'data' => '请完整选择产品规格!'];
                        }
                    }
                }

                DB::beginTransaction(); //开启事务
                $goods = $ShopGoodsModel->get_goods('', $goodsIds);
                $totalPrice = 0;   //总价格
                $number = 0;
//                $freight = 0;//运费
//                $weight = 0;//重量0.
//                $freight_cost = 1;//是否需要算运费
                foreach ($goods as $k => $v) {
                    foreach ($data['goods'] as $key => $val) {
                        if ($val['goodsid'] == $v['id']) {
                            $number += $val['number'];
                            $freight = $v['is_gift'];
//                            var_dump($val['number']);exit;
                            $data['goods'][$key]['sold'] = $val['number'] + $v['sold'];
                            $totalPrice += (intval($val['number']) * $v['rulingprice']);
                            $data['goods'][$key]['price'] = $v['rulingprice'];
                            $data['goods'][$key]['totalcnf'] = $v['totalcnf']; //0 拍下减库存 1 付款减库存 2 永久不减
                            $data['goods'][$key]['total'] = $v['total'];
                            $data['goods'][$key]['goodsname'] = $v['goodsname']; //商品名字
                        }
                    }
                }
                //创建订单
                $order = [
                    'uid' => $user->uid,
                    'openid' => $user->openid,
                    'ordertype' => 3, //1 优品特选 2 特价专区 3 0元商城
                    'ordersn' => ORDER_SN(),
                    'price' => $totalPrice,
                    'originalprice' => $totalPrice,
                    'freight' => $freight, //运费
                    'company_id' => $user->company_id, //公司id
                    'status' => 0,//-1取消状态，0代付款，1为已付款，2为已发货，3为成功
                    'createtime' => time()
                ];
                $orderID = $ShopOrderModel->add_order($order);


                if ($orderID) {

                    $cart = array(); //购物车id
                    $orderComment = array();
                    foreach ($data['goods'] as $key => $val) {
                        $cart[] = $val['id']; //获取购物车id
                        $orderComment[] = [
                            'uid' => $user->uid,
                            'orderid' => $orderID,
                            'openid' => $user->openid,
                            'goodsid' => $val['goodsid'],
                            'price' => $val['price'],
                            'goodsname' => $val['goodsname'],
                            'number' => $val['number'],
                            'specs' => $val['specs'],
                            'createtime' => time(),
                        ];
                    }

                    if (!empty($orderComment)) {
                        $rico = $ShopOrderCommentModel->insert($orderComment);
                        if ($rico) {
                            //直接购买
                            if (isset($data['type'])) {
                                DB::commit();  //提交
                                return ['code' => 1, 'data' => ['id' => $orderID, 'data' => '添加成功']];
                            }
                            //删除购物车
                            $Comment = $ShopMemberCartModel->delete_cart($cart);
                            if ($Comment) {
                                DB::commit();  //提交
                                return ['code' => 1, 'data' => ['id' => $orderID, 'data' => '添加成功']];
                            } else {
                                DB::rollback();  //回滚
                                return ['code' => 0, 'data' => '购物车已清空'];
                            }
                        } else {
                            DB::rollback();  //回滚
                            return ['code' => 0, 'data' => '添加失败'];
                        }
                    }
                } else {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '设置失败'];
                }
                break;

        }
    }

    /**
     * 支付页面
     */
    public function order()
    {
        return view('Home.micro.order');
    }

    public function payOrder(Request $request)
    {
        $data = $request->all();
        if (empty($data)) {
            return ['code' => 0, 'data' => '数据错误11'];
        }
        switch ($data['class']) {
            case 'add': //添加
                break;
        }
    }
}